// packageA/pages/addWork/addWork.js
const db = wx.cloud.database()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    fileList: [],
    max: 300,
    text: '',
    cursor: 0,
    loading: false,
    selectList: [],
    workList: [],
    workLableList: [],
    isWork: false
  },
  afterRead(event){
    let oldData = this.data.fileList
    let newData = oldData.concat(event.detail.file)
    this.setData({ fileList: newData });
  },
  deleteImg(e){
    let list = this.data.fileList
    list.forEach((val,index)=>{
      if(val.url == e.detail.file.url){
        list.splice(index, 1);
      }
    })
    this.setData({ fileList: list });
  },
  gettextarea(e){
    this.setData({
      text: e.detail.value,
      cursor: e.detail.cursor
    })
  },
  sumbit(){
    if(this.data.workList .length == 0){
      wx.showToast({ title: '请选择工地', icon: 'none' });
      return
    }
    if (!this.data.text) {
      wx.showToast({ title: '请输入', icon: 'none' });
      return
    }
    if (this.data.fileList.length == 0) {
      wx.showToast({ title: '请选择图片', icon: 'none' });
      return
    }
    this.setData({
      loading: true
    })
    this.uploadToCloud()
  },
  getSelectList(e){
    this.setData({
      workList: e.detail.map(i=>{return i.id}),
      workLableList: e.detail.map(i=>{return i.name})
    })
  },
  // 上传图片
  uploadToCloud() {
    let userInfo = JSON.parse(wx.getStorageSync('userInfo'))
    const fileList = this.data.fileList
    let openid = userInfo._openid
    let uploadTasks = []
    let date = Date.now()
    fileList.forEach((file, index) => {
      let name = openid + '.' + date + '.' + index +  '.png'
      uploadTasks.push(this.uploadFilePromise(name, file))
    });
    let that = this
    Promise.all(uploadTasks)
    .then(res => {
      let data = {
        avater: userInfo.avater,
        content: that.data.text,
        date:  that.timestampToTime(date),
        nickname: userInfo.name,
        imgList: res.map(i => { return i.fileID}),
        workList: that.data.workList,
        workLableList: that.data.workLableList
      }
      if(!that.data.isWork){
        db.collection('workList').add({data: data}).then(r=>{
          wx.showToast({ title: '提交成功', icon: 'none' });
          setTimeout(()=>{
            wx.reLaunch({
              url: '/pages/work/work',
              success:(res)=>{
                that.setData({
                  loading: false
                })
              }
            })
          },500)
        }).catch(e=>{
          wx.showToast({ title: '提交失败', icon: 'none' });
          that.setData({
            loading: false
          })
        })
      }else {
        db.collection('pastCases').add({data: data}).then(r=>{
          wx.showToast({ title: '提交成功', icon: 'none' });
          setTimeout(()=>{
            wx.reLaunch({
              url: '/pages/pastCases/pastCases',
              success:(res)=>{
                that.setData({
                  loading: false
                })
              }
            })
          },500)
        }).catch(e=>{
          wx.showToast({ title: '提交失败', icon: 'none' });
          that.setData({
            loading: false
          })
        })
      }
      
    })
    .catch(e => {
      wx.showToast({ title: '上传失败', icon: 'none' });
      that.setData({
        loading: false
      })
    });
  },
  timestampToTime(timestamp) {
    timestamp = timestamp ? timestamp : null;
    let date = new Date(timestamp);//时间戳为10位需*1000，时间戳为13位的话不需乘1000
    let Y = date.getFullYear() + '-';
    let M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
    let D = (date.getDate() < 10 ? '0' + date.getDate() : date.getDate()) + ' ';
    let h = (date.getHours() < 10 ? '0' + date.getHours() : date.getHours()) + ':';
    let m = (date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()) + ':';
    let s = date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds();
    return Y + M + D + h + m + s;
  },
  uploadFilePromise(fileName, chooseResult) {
    return wx.cloud.uploadFile({
      cloudPath: fileName,
      filePath: chooseResult.url
    });
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    if(options.isWork){
      this.setData({isWork: true})
    }
    this.getworkList()
  },
  getworkList(){
    let count = 0
    db.collection('siteInfo').count().then(res=>{
      count = res.total
      if(count > 0){
        let asycList = []
        for(let i = 0; i < count; i += 20){
          asycList.push(new Promise((resolve, reject) => {
            db.collection('siteInfo').orderBy('date', 'desc').skip(i).get({
              success:function(res) {
                resolve(res.data)
              }
            })
          }))
        }
        Promise.all(asycList).then(res=>{
          console.log(res[0]);
          this.setData({selectList: res[0]})
        })
      }
    })

  },
  close(){
    this.selectComponent('#mySelect').close()
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {
    
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },
  bindTextAreaBlur(){

  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})